import React from 'react';
import Resumablejs from 'resumablejs';
import Upload from '@/zero/components/Upload';

/**
 * 增强 Upload => 分片上传
 */
const Index = props => {
  const { extConfig, ...rest } = props;
  return (
    <>
      <Upload
        customRequest={config => {
          const {
            method,
            action,
            data,
            headers,
            withCredentials,
            filename,
            file,
            onProgress,
            onSuccess,
          } = config;

          const r = new Resumablejs({
            uploadMethod: method,
            target: action,
            query: data,
            headers,
            withCredentials,
            fileParameterName: filename,

            chunkSize: 5 * 1024 * 1024,

            chunkNumberParameterName: 'chunk',
            totalChunksParameterName: 'chunks',
            chunkSizeParameterName: 'chunkSize',
            currentChunkSizeParameterName: 'currentChunkSize',
            totalSizeParameterName: 'size',
            identifierParameterName: 'uuid',
            fileNameParameterName: 'name',
            relativePathParameterName: 'relativePath',
            typeParameterName: 'type',

            testChunks: false,
            ...extConfig,
          });

          r.addFile(file);

          r.on('fileAdded', () => {
            r.upload();
          });
          r.on('fileProgress', resumableFile => {
            onProgress({ percent: resumableFile.progress() * 100 });
          });
          r.on('fileSuccess', (resumableFile, responseBody) => {
            onSuccess(responseBody, resumableFile.file);
          });
        }}
        {...rest}
      />
    </>
  );
};

Index.displayName = 'ChunkUpload';
export default Index;
